package connect

import (
	"encoding/json"
	"fmt"
	"ghw2/namesrv/Mapper"
	"ghw2/util"
	"net"
	"time"
)

func ServerConnProcess(conn *net.Conn) {
	defer func() {
		(*conn).Close()
		if err := recover(); err != nil {
			fmt.Println("服务端连接崩溃:" + (*conn).RemoteAddr().String())
			fmt.Println(err)
			fmt.Println()
		}
	}()

	buffer := make([]byte, 1023)
	n, err := (*conn).Read(buffer)
	if err != nil {
		panic(err)
	}

	serverAddr := string(buffer[:n])

	_, err = (*conn).Write([]byte("ok"))
	if err != nil {
		panic(err)
	}

	var services []string
	n, err = (*conn).Read(buffer)
	if err != nil {
		panic(err)
	}

	json.Unmarshal(buffer[:n], &services)

	fmt.Println("Receive services list from address", (*conn).RemoteAddr().String(), services)
	for _, service := range services {
		fmt.Println("Get service ", service)
		if v, ok := Mapper.ServiceAddressMapper[service]; ok {
			if !util.IsInArray(v.Addresses, serverAddr) {
				v.Addresses = append(v.Addresses, serverAddr)
			}
		} else {
			var serviceAddressMapper Mapper.ServiceAddressMapperType
			serviceAddressMapper.Addresses = append(serviceAddressMapper.Addresses, serverAddr)
			Mapper.ServiceAddressMapper[service] = &serviceAddressMapper
		}
	}

	var addressServiceMapper Mapper.AddressServiceMapperType
	addressServiceMapper.Services = services
	addressServiceMapper.UpdateAt = time.Now()
	Mapper.AddressServiceMapper[serverAddr] = &addressServiceMapper

	// 心跳循环
	for {
		n, err := (*conn).Read(buffer)
		if err != nil {
			panic(err)
		}
		if string(buffer[:n]) == "ping" {
			Mapper.AddressServiceMapper[serverAddr].UpdateAt = time.Now()
		}
	}

}
